//
//  XMMemberViewController.m
//  XunMi
//
//  Created by MacBook on 2024/4/17.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMMemberViewController.h"
#import "XMMemberModel.h"
#import "XMMemberCollectionViewCell.h"
#import "XMMemberDescCollectionViewCell.h"
#import "YHIAPManager.h"


@interface XMMemberViewController () <UICollectionViewDelegate ,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UIImageView *memberImgV;
@property (weak, nonatomic) IBOutlet UILabel *memberTipLa;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionView *descCollectionView;
@property (weak, nonatomic) IBOutlet UIButton *openButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *descH;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionTopSpace;
@property (weak, nonatomic) IBOutlet UILabel *tequanLa;

@property (nonatomic, strong) NSArray <XMMemberModel *> *dataArray;
@property (nonatomic, strong) NSArray <XMMemberItemModel *> *descArray;

@end

@implementation XMMemberViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSubviews];
    [self mineUserInfo];
    [self memberData];
}

- (void)mineUserInfo {
    NSMutableDictionary *dic = @{
        @"module": @"4"
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/user/obtain" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            XMUserModel *model = [XMUserModel mj_objectWithKeyValues:result];
            if ([XMUtil isBlankString:model.member_time]) {
                self.memberImgV.image = kGetImage(@"member_0");
                self.memberTipLa.text = @"您还不是会员，会员权益更多";
                self.memberTipLa.textColor = k1F1F1F;
                [self.openButton setTitle:@"立即开通" forState:UIControlStateNormal];
            } else {
                self.memberImgV.image = kGetImage(@"member_1");
                self.memberTipLa.text = model.member_time;
                self.memberTipLa.textColor = kHEX(@"#FBCF8E");
                [self.openButton setTitle:@"立即续费" forState:UIControlStateNormal];
            }
        }
    }];
}

- (void)memberData {
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    NSMutableDictionary *dic = @{}.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/config/memberList" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            self.dataArray = [XMMemberModel mj_objectArrayWithKeyValuesArray:result[@"record"]];
            [self.collectionView reloadData];
            [self.descCollectionView reloadData];
            self.dataArray.firstObject.selected = YES;
            self.collectionTopSpace.constant = self.dataArray.firstObject.settle_days.intValue > 0 ? 38 : 10;
            self.tequanLa.hidden = self.dataArray.firstObject.settle_days.intValue == 0;
            self.tequanLa.text = kStringFormat(@"会员特权卡，每%@天发放一次", self.dataArray.firstObject.settle_days);
            
            self.descArray = self.dataArray.firstObject.content;
            double number = self.descArray.count / 2.0;
            double roundedNumber = ceil(number);
            self.descH.constant = roundedNumber * 64 + (roundedNumber - 1) * 0;
        }
    }];
}

#pragma mark - setupSubViews
- (void)setupSubviews {
    self.navView.backgroundColor = UIColor.clearColor;
    [self.navLeft2Btn setTitle:@"我的会员" forState:UIControlStateNormal];
    [self.navRightBtn setTitle:@"购买记录" forState:UIControlStateNormal];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(98, 100);
    layout.minimumLineSpacing = 14;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.collectionView setCollectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerNib:kNibWithName(kStringFromClass(XMMemberCollectionViewCell)) forCellWithReuseIdentifier:kStringFromClass(XMMemberCollectionViewCell)];
    
    UICollectionViewFlowLayout *descLayout = [[UICollectionViewFlowLayout alloc] init];
    descLayout.itemSize = CGSizeMake((kScreenWidth - 40 - 5) / 2, 64);
    descLayout.minimumLineSpacing = 0;
    descLayout.minimumInteritemSpacing = 5;
    
    [self.descCollectionView setCollectionViewLayout:descLayout];
    self.descCollectionView.delegate = self;
    self.descCollectionView.dataSource = self;
    
    [self.descCollectionView registerNib:kNibWithName(kStringFromClass(XMMemberDescCollectionViewCell)) forCellWithReuseIdentifier:kStringFromClass(XMMemberDescCollectionViewCell)];
}

#pragma mark - Actions
- (IBAction)open:(UIButton *)sender {
    XMMemberModel *model;
    for (XMMemberModel *object in self.dataArray) {
        if (object.selected) {
            model = object;
            break;
        }
    }
    if (![NSString isEmpty:model.product_id]) {
        [[YHNetworkManager sharedInstance] postWithUrl:@"api/money/prepareOrder" parameters:@{@"index": model.index, @"type": @(2), @"coupon": @(0), @"method": @"appstore"}.mutableCopy completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
            if (tip.success) {
                NSString *orderId = [result toString:@"order_sn"];
                [self applePayWith:model.product_id orderId:orderId];
            }
        }];
    }
}

- (void)applePayWith:(NSString *)productId orderId:(NSString *)orderId {
    [MBProgressHUD showHUDActivityMsg:nil];
    XMWeakSelf(self);
    [[YHIAPManager sharedInstance] startPurchaseWithProductId:productId
                                                      orderId:orderId
                                               completeHandle:^(YHIAPPurchType type, NSData *_Nonnull data) {
        XMStrongSelf(self);
        [MBProgressHUD hideHUD];
        if (type == IAPPurchFailed) {
            [MBProgressHUD showHUDMsg:@"充值失败" toView:nil];
        }
        if (type == IAPPurchCancel) {
            [MBProgressHUD showHUDMsg:@"取消充值" toView:nil];
        }
        
        if (type == IAPPurchVerSuccess) {
            [MBProgressHUD showHUDMsg:@"充值成功" toView:nil completionBlock:^{
                [self memberData];
                [self mineUserInfo];
            }];
            
        }
        
    }];
}


- (IBAction)sel:(UIButton *)sender {
    sender.selected = !sender.selected;
}

- (IBAction)re:(UIButton *)sender {
    XMWebViewController *vc = [[XMWebViewController alloc] init];
    vc.titleStr = @"充值协议";
    vc.urlStr = kGlobalVariables.appConfig.privacy.rechargeAgreement;
    vc.needNav = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)mem:(id)sender {
    XMWebViewController *vc = [[XMWebViewController alloc] init];
    vc.titleStr = @"会员协议";
    vc.urlStr = kGlobalVariables.appConfig.privacy.membersAgreement;
    vc.needNav = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.collectionView == collectionView) {
        return self.dataArray.count;;
    }
    return self.descArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.collectionView == collectionView) {
        XMMemberCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kStringFromClass(XMMemberCollectionViewCell) forIndexPath:indexPath];
        cell.model = [self.dataArray safe_objectAtIndex:indexPath.item];
        return cell;
    }
    
    XMMemberDescCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kStringFromClass(XMMemberDescCollectionViewCell) forIndexPath:indexPath];
    cell.model = [self.descArray safe_objectAtIndex:indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.collectionView == collectionView) {
        [self.dataArray enumerateObjectsUsingBlock:^(XMMemberModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (indexPath.item == idx) {
                obj.selected = YES;
                self.descArray = obj.content;
                self.collectionTopSpace.constant = obj.settle_days.intValue > 0 ? 38 : 10;
                self.tequanLa.hidden = obj.settle_days.intValue == 0;
                self.tequanLa.text = kStringFormat(@"会员特权卡，每%@天发放一次", obj.settle_days);
            } else {
                obj.selected = NO;
            }
        }];
        [self.collectionView reloadData];
        [self.descCollectionView reloadData];
    }
}

@end
